<script setup>
import { reactive } from 'vue'
import { to } from 'sf-utils2'
import { ElMessage } from 'element-plus'
import SvgIcon from '@/components/svg-icon/index.vue'
import loginApi from '@/api/modules/user-center/login'
import { encrypt } from '@/utils/jsencrypt'
import useUserStore from '@/store/use-user-store'
import useRouterPlus from '@/router/use-router-plus'
import { useVerifyCode } from '@shared/hooks/use-verify-code'
import { rules, pattern } from '@shared/base/base-form/rules'

const userStore = useUserStore()
const { router } = useRouterPlus()

const { start, time } = useVerifyCode()

const formProps = reactive({
  /**
   * 表单实例
   * @type {FormInstance}
   */
  instanceRef: null,
  /**
   * 表单数据
   */
  model: {},

  /**
   * 表单验证规则
   */
  rules: {
    mobile: [{ required: true, message: '请输入手机号', trigger: 'change' }, ...rules.phone],
    password: [{ required: true, message: '请输入密码', trigger: 'change' }],
    code: [{ required: true, message: '请输入验证码', trigger: 'change' }]
  },

  loading: false,

  /** 登录方式 */
  loginWay: 'password',

  /** 发送验证码loading */
  sendMsgLoading: true
})

/**
 * 发送验证码
 * @return {Promise<*>}
 */
async function onSendMsg() {
  if (time.value > 0) return
  const mobile = formProps.model?.mobile
  if (!mobile) return ElMessage.error('请输入手机号')
  if (!pattern.phone.test(mobile)) return ElMessage.error('手机号格式错误')
  formProps.sendMsgLoading = true
  const [res, err] = await to(loginApi.captchaSms({ mobile }))
  formProps.sendMsgLoading = false
  if (err || res?.code !== 200) return ElMessage.error(res?.message || String(err))
  ElMessage.success('验证发送成功，请注意查收')
  start()
}

/**
 * 忘记密码
 */
function onForgetPsd() {
  router.push({
    path: '/login/forget-pass'
  })
}

/**
 * 表单验证规则
 */
async function onSubmit() {
  const [valid, errorFields] = await to(formProps.instanceRef.validate())
  if (!valid) {
    // 校验不通过，提示文字
    const first = Object.values(errorFields).flat().shift()
    return ElMessage.error({
      message: first?.message,
      duration: 5000
    })
  }

  formProps.loading = true

  let reqData

  if (formProps.loginWay == 'password') {
    // 密码登录
    reqData = {
      mobile: formProps.model?.mobile,
      password: encrypt(formProps.model?.password),
      loginType: 'PASSWORD'
    }
  } else {
    // 验证码登录
    reqData = {
      mobile: formProps.model?.mobile,
      verifyCode: formProps.model?.mobile,
      loginType: 'SMS'
    }
  }
  const [res, err] = await to(loginApi.login(reqData))
  formProps.loading = false
  if (err || res?.code !== 200) return ElMessage.error(res?.message || String(err))

  ElMessage.success('登录成功')
  userStore.token = res?.data?.token
  router.push('/home')
  // 校验通过，提交表单
  console.log('提交表单', formProps.model)
}
</script>

<template>
  <main class="page">
    <article class="page__banner hidden min-w-[576px] px-14 py-12 lg:block">
      <img
        src="@/assets/imgs/login/zslogo.svg"
        alt="浙商logo"
        class="h-[26px] w-[122px]"
      >
    </article>

    <article class="flex flex-1 flex-col items-center justify-center bg-white">
      <!--标题-->
      <header
        class="flex gap-4 text-[28px] font-medium leading-9"
        aria-label="title"
      >
        <h1 id="title">
          欢迎登录个综服平台
        </h1>
        <span class="self-center rounded bg-orange-50 px-[10px] py-1 text-base text-orange"> 资管端 </span>
      </header>

      <!--表单-->
      <el-form
        :ref="(el) => (formProps.instanceRef = el)"
        class="mt-20px flex w-[336px] flex-col"
        :model="formProps.model"
        :rules="formProps.rules"
        @keydown.enter="onSubmit"
      >
        <el-tabs
          v-model="formProps.loginWay"
          class="ijep-tabs--tzx-large"
        >
          <!-- 手机密码登录   -->
          <el-tab-pane
            name="password"
            label="密码登录"
          >
            <template v-if="formProps.loginWay == 'password'">
              <!--手机号-->
              <el-form-item
                prop="mobile"
                required
              >
                <el-input
                  v-model.trim="formProps.model.mobile"
                  type="text"
                  class="h-12 w-full"
                  placeholder="手机号"
                  aria-label="手机号"
                  name="username"
                  autocomplete="username"
                  clearable
                >
                  <template #prefix>
                    <SvgIcon
                      svg="login/account"
                      size="16"
                    />
                  </template>
                </el-input>
              </el-form-item>

              <!--密码-->
              <el-form-item
                prop="password"
                required
              >
                <el-input
                  v-model.trim="formProps.model.password"
                  type="password"
                  class="h-12 w-full"
                  placeholder="密码"
                  aria-label="手机号"
                  autocomplete="current-password"
                  clearable
                  show-password
                >
                  <template #prefix>
                    <SvgIcon
                      svg="login/password"
                      size="16"
                    />
                  </template>
                </el-input>
              </el-form-item>
            </template>
          </el-tab-pane>

          <!--  短信登录   -->
          <el-tab-pane
            name="sms"
            label="验证码登录"
          >
            <template v-if="formProps.loginWay == 'sms'">
              <!--手机号-->
              <el-form-item
                prop="mobile"
                required
              >
                <el-input
                  v-model="formProps.model.mobile"
                  type="text"
                  class="h-12 w-full"
                  placeholder="手机号"
                  aria-label="手机号"
                  name="mobile"
                  autocomplete="mobile"
                  clearable
                >
                  <template #prefix>
                    <SvgIcon
                      svg="login/account"
                      size="16"
                    />
                  </template>
                </el-input>
              </el-form-item>

              <!--验证码-->
              <el-form-item prop="code">
                <el-input
                  v-model="formProps.model.code"
                  type="text"
                  class="w-50 h-12"
                  placeholder="验证码"
                  aria-label="验证码"
                  autocomplete="one-time-code"
                >
                  <template #prefix>
                    <SvgIcon
                      svg="login/verify"
                      size="16"
                    />
                  </template>
                </el-input>

                <div
                  v-spin="{ loading: formProps.sendMsgLoading, size: 'small' }"
                  :class="[
                    `flex-center w-30 ml-4 h-full cursor-pointer rounded bg-primary-50 text-center text-base font-bold leading-10 text-primary`,
                    time == 0 && `cursor-not-allowed bg-[#F4F5F9] text-[#BFBFBF]`
                  ]"
                  @click="onSendMsg"
                >
                  {{ time > 0 ? `${time}s` : '获取验证码' }}
                </div>
              </el-form-item>
            </template>
          </el-tab-pane>
        </el-tabs>

        <div class="pb-24px">
          <el-link
            type="primary"
            :underline="false"
            @click="onForgetPsd"
          >
            忘记密码？
          </el-link>
        </div>

        <!--记住密码-->
        <el-form-item
          v-if="false"
          prop="remember"
        >
          <el-checkbox v-model="formProps.model.remember">
            记住密码
          </el-checkbox>
        </el-form-item>

        <el-button
          class="h-12 w-full text-base"
          type="primary"
          :loading="formProps.loading"
          @click="onSubmit"
        >
          登 录
        </el-button>
      </el-form>
    </article>
  </main>
</template>

<style scoped lang="less">
.page {
  inline-size: 100vw;
  block-size: 100vh;
  display: flex;
}

.page__banner {
  inline-size: 40%;
  background-image: url('@/assets/imgs/login/background.svg');
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center;
}

// ---------------------------设置输入框图标颜色-------------------------------
.ijep-form-item :deep(.ijep-input__prefix-inner) {
  transition: color 0.3s;
}

// 设置输入框图标颜色 选中状态颜色
.ijep-form-item:focus-within :deep(.ijep-input__prefix-inner) {
  color: var(--tzx-primary-color);
}

// 设置输入框图标颜色 错误状态颜色
.ijep-form-item.is-error :deep(.ijep-input__prefix-inner) {
  color: var(--tzx-error-color);
}

// --------------------autocomplete------------------------------------
:deep(.ijep-input__wrapper):has(:-webkit-autofill) {
  // 自动填充背景色
  background-color: var(--tzx-primary-color-50);
}

:deep(.ijep-tabs) {
  &.ijep-tabs--tzx-large.ijep-tabs--top {
    height: auto;
    min-height: var(--tzx-tab-height);
  }

  .ijep-tabs__nav-scroll {
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .ijep-tabs__nav-wrap {
    &::after {
      display: none;
    }
  }

  .ijep-tabs__content {
    padding-top: 20px;
    overflow: visible;
  }
}
</style>
